import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions,URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/share';
import {Subject} from"rxjs/Subject";

import {GlobalVariable} from "../global.config";


@Injectable()
export class HttpRequest{
  private outputTitle = new Subject();
  public baseUrl = GlobalVariable.BASE_API_URL;
  headers = new Headers();

  constructor(
    private http:Http
  ){
    this.headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  }

  output$ = this.outputTitle.asObservable();

  sendPost(action:string,param:Object={},type:string=''):Observable<any>{

    this.setHeader();

    //console.log("send before transform:"+JSON.stringify(param));
    let body = this.postConfig(param);
    //noinspection TypeScriptUnresolvedFunction
    return this.http
      .post(this.baseUrl + action,body,{headers:this.headers})
      .map((res:Response) => {
        let result=res.json();
        //console.log(result);
        if(result.resultStatus == '200') this.outputTitle.next(result);
        //if(type != '') this.outputTitle.next(result);

        return result;
      })
      .catch((error:any)=>this.handleError(error))
      .share();
  }

  sendGet(action:string,param:Object={},type:string=''):Observable<any>{

    this.setHeader();

    let body = param=={} ? '':'?' + this.postConfig(param);
    //noinspection TypeScriptUnresolvedFunction
    return this.http
      .get(this.baseUrl + action + body,{headers:this.headers})
      .map((res:Response) => {
        let result=res.json();
        //console.log(result);
        if(result.resultStatus == '200') this.outputTitle.next(result);
        //if(type != '') this.outputTitle.next(result);

        return result;
      })
      .catch((error:any)=>this.handleError(error))
      .share();
  }




  sendPut(action:string,param:Object={},type:string=''):Observable<any>{

    this.setHeader();

    let body = this.postConfig(param);
    //noinspection TypeScriptUnresolvedFunction
    return this.http
      .put(this.baseUrl + action,body,{headers:this.headers})
      .map((res:Response) => {
        let result=res.json();
        //console.log(result);
        if(result.resultStatus == '200') this.outputTitle.next(result);
        //if(type != '') this.outputTitle.next(result);

        return result;
      })
      .catch((error:any)=>this.handleError(error))
      .share();
  }

  sendDelete(action:string,param:Object={},type:string=''):Observable<any>{

    this.setHeader();

    let body = param=={} ? '':'?' + this.postConfig(param);
    //noinspection TypeScriptUnresolvedFunction
    return this.http
      .delete(this.baseUrl + action + body,{headers:this.headers})
      .map((res:Response) => {
        let result=res.json();
        //console.log(result);
        if(result.resultStatus == '200') this.outputTitle.next(result);
        //if(type != '') this.outputTitle.next(result);

        return result;
      })
      .catch((error:any)=>this.handleError(error))
      .share();
  }

  gettoday():string{
    let getdata = new Date();
    let year = getdata.getFullYear();
    let day = getdata.getDate();
    let month = getdata.getMonth()+1;
    let hours = getdata.getHours();
    let minutes = getdata.getMinutes();
    let secondes = getdata.getSeconds();
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + secondes ;
  }

  private setHeader(){
    let token:string = localStorage.getItem("token");

    if(!this.headers.has('AUTHORIZATION') && token != null){
      this.headers.append('AUTHORIZATION','token '+token);
    }
  }

  private handleError(err:any) {
    console.log('sever error:', err);  // debug
    if(err instanceof Response) {
      return Observable.throw(err.json().error || 'backend server error');
      // if you're using lite-server, use the following line
      // instead of the line above:
      //return Observable.throw(err.text() || 'backend server error');
    }
    return Observable.throw(err || 'backend server error');
  }


  private postConfig(url_obj){
    var res_arr = [];
    for(let key in url_obj){
      var str = encodeURIComponent(key) +
        "=" + encodeURIComponent(url_obj[key]);
      res_arr.push(str);
    }
    return res_arr.join("&");
  }


}
